;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.MaterialTransfer", [])
        .controller("MaterialTransferCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService) {
            $scope.activeFlag = [true, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                curRow: 0,
                allChecked: false
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.dataList = [];
            $scope.detailDataList = [];
            $scope.transferObj = {
                headerInfo: {},
                detailList: []
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/materialTransfer/exportAll")
            };
            $scope.tableConfig = {
                fixedWidth: 200,
                scrollWidth: 1000,
                tableCol: [
                    {
                        type: "",
                        name: "转库单号",
                        dataField: "transferOrder",
                        width: 200,
                        isShow: true,
                        isFixed: true,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "转库类型",
                        dataField: "typeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "原储位",
                        dataField: "preLocationCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "新储位",
                        dataField: "newLocationCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单部门",
                        dataField: "deptName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP同步状态",
                        dataField: "stateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件凭证",
                        dataField: "voucherNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP错误信息",
                        dataField: "sapErrorMsg",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    }
                ]
            };
            $scope.detailTbConf = {
                scrollWidth: 700,
                tableCol: [
                    {
                        type: "",
                        name: "零件条码",
                        dataField: "barcode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件分类",
                        dataField: "materialType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "计量单位",
                        dataField: "unit",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "数量",
                        dataField: "amount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.sapState = [
                {id: 0, name: "未同步"},
                {id: 1, name: "同步成功"},
                {id: 2, name: "同步失败"},
                {id: 3, name: "不需同步"}
            ];
            $scope.addInfo = {
                type: 1,
                materialList: []
            };
            $scope.tableMaterialConfig = {
                scrollWidth: 410,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "库存",
                        dataField: "amount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "转移数量",
                        dataField: "amounts",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                        isInput: true
                    }
                ]
            };
            $scope.submitted = false;

            function initData() {
                $scope.detailDataList = [];
                $scope.transferObj = {
                    headerInfo: {},
                    detailList: []
                };
            }

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:

                        break;
                    default:
                        break;
                }
            };

            var btnPermissionCode = {
                materialTransferExport: window.ActionCode.materialTransferExport,
                materialTransferAdd: window.ActionCode.materialTransferAdd
            };

            $scope.btnPermission = {
                materialTransferExport: true,
                materialTransferAdd: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            function getDataList(curPage) {
                var service = "device";
                var reqUrl = "/materialTransfer/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.typeShow = item.type === 0 ? "零件转移" : "储位转移";
                        item.stateShow = $filter("ProgressStatus")(item.sapStatus, "synStatus");
                        item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(1, item);
                        break;
                    default:
                        break;
                }
            };

            $scope.addData = function () {
                $scope.addInfo = {
                    type: 1,
                    materialList: []
                };
                $scope.changeTab(2);
            };

            $scope.selectWarehouse = function (type) {
                var lastDepot = type === 'old' ? $scope.addInfo.oldDepot : $scope.addInfo.newDepot;
                ybWidget.WarehouseASelector().then(function (data) {
                    if (lastDepot === data.warehouseCode) {
                        return;
                    }
                    if (type === 'old') {
                        $scope.addInfo.oldDepot = data.warehouseCode;
                        $scope.addInfo.oldLocationCode = '';
                        $scope.addInfo.materialList = [];
                    } else {
                        $scope.addInfo.newDepot = data.warehouseCode;
                        $scope.addInfo.newLocationCode = '';
                    }
                })
            };

            $scope.clearWarehouse = function (type) {
                if (type === 'old') {
                    $scope.addInfo.oldDepot = '';
                    $scope.addInfo.oldLocationCode = '';
                    $scope.addInfo.materialList = [];
                } else {
                    $scope.addInfo.newDepot = '';
                    $scope.addInfo.newLocationCode = '';
                }
            };

            function getMaterialByLocation() {
                var service = "device";
                var reqUrl = "/warehouseInventory/list";
                var param = {pageSize: 0, pageNum: 0, filters: {locationCodes: $scope.addInfo.oldLocationCode}};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        return;
                    }
                    resp.value.list.forEach(function (item) {
                        item.amounts = item.amount;
                    });
                    $scope.addInfo.materialList = resp.value.list;
                });
            }

            $scope.selLocation = function (type) {
                if(!$scope.addInfo.oldDepot){
                    ybWidget.ShowMessage("请先选择原仓库！");
                    return;
                }
                var depotCode = type === "old" ? $scope.addInfo.oldDepot : $scope.addInfo.newDepot;
                var lastLocation = type === 'old' ? $scope.addInfo.oldLocationCode : $scope.addInfo.newLocationCode;
                var param = {
                    reqUrl: '/warehouse/findAbleAreaCodeList',
                    warehouseCode: depotCode
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    if (lastLocation === data.locationCode) {
                        return;
                    }
                    if (type === 'old') {
                        $scope.addInfo.oldLocationCode = data.locationCode;
                        $scope.addInfo.materialList = [];
                        getMaterialByLocation();
                    } else {
                        $scope.addInfo.newLocationCode = data.locationCode;
                    }
                })
            };

            $scope.clearLocation = function (type) {
                if (type === 'old') {
                    $scope.addInfo.oldLocationCode = '';
                    $scope.addInfo.materialList = [];
                } else {
                    $scope.addInfo.newLocationCode = '';
                }
            };

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    $scope.markInfo.allChecked = checkAll();

                }
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.addInfo.materialList.length; i < len; i++) {
                    if (!$scope.addInfo.materialList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function () {
                angular.forEach($scope.addInfo.materialList, function (item) {
                    item.isChecked = $scope.markInfo.allChecked;
                });
            };

            function setTransferMaterialList() {
                var materialList = [];
                if ($scope.addInfo.type == 1) {
                    // 全
                    $scope.addInfo.materialList.forEach(function (item) {
                        var materialItem = {
                            materialNo: item.materialNo,
                            amounts: item.amounts
                        };
                        materialList.push(materialItem)
                    });
                }
                if ($scope.addInfo.type == 0) {
                    // 部分
                    $scope.addInfo.materialList.forEach(function (item) {
                        if (item.isChecked) {
                            var materialItem = {
                                materialNo: item.materialNo,
                                amounts: item.amounts
                            };
                            materialList.push(materialItem)
                        }
                    });
                }
                return materialList;
            }

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if (!!$scope.addInfo.newLocationCode && ($scope.addInfo.oldLocationCode === $scope.addInfo.newLocationCode)) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/warehouseInventory/transferWarehouseInventoryWithoutBarCode";
                var param = {
                    type: parseInt($scope.addInfo.type),
                    oldLocationCode: $scope.addInfo.oldLocationCode,
                    newLocationCode: $scope.addInfo.newLocationCode,
                    materialNoAndAmounts: setTransferMaterialList()
                };
                if (param.materialNoAndAmounts.length === 0) {
                    ybWidget.ShowMessage("请选择需要转库的零件", MESG_TYPE.Note);
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message,MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList(1);
                    $scope.cancelSaveData();
                });
            };

            $scope.cancelSaveData = function () {
                $scope.addInfo = {};
                $scope.changeTab(0);
            };

            function viewDetail(curPage, item) {
                var service = "device";
                var reqUrl = "/materialTransfer/item";
                var param = {};
                param.id = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        return;
                    }
                    $scope.changeTab(1);
                    $scope.detailPageInfo.totalRows = resp.value.total;
                    $scope.detailPageInfo.totalPages = resp.value.pages;
                    $scope.transferObj = resp.value;
                    $scope.transferObj.headerInfo.stateShow = $filter("ProgressStatus")($scope.transferObj.headerInfo.sapStatus, "synStatus");
                });
            }

            $scope.searchDetail = function () {
                viewDetail();
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
